/**
 * Copyright ©2003~2019年4月30日 szkingdom
 * @author raohj
 * @date 2019年4月30日
 * @file RCountDownLatch.java
 * @comment : please input your comment to this file
 * @version : input version
 * @modify:
 * 		1、 2019年4月30日 由 raohj 新建文件
 */
package com.ccnu.demojava.concurrent.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author raohj
 * @date 2019年4月30日
 * @version
 * @comment to add your comment
 */
public class RCountDownLatch {
	private static final Logger log = LoggerFactory.getLogger(RCountDownLatch.class);

	// 老板线程，等待任务执行完毕
	public static class RCntDownLatchBoss implements Runnable {
		private final CountDownLatch cdl;

		public RCntDownLatchBoss(CountDownLatch cdl) {
			this.cdl = cdl;
		}

		@Override
		public void run() {
			// 等待完成
			try {
				cdl.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			log.info("等待的任务执行完毕");
		}
	}

	// 工作线程，执行任务
	public static class RCntDownLatchWork implements Runnable {
		private final CountDownLatch cdl;

		public RCntDownLatchWork(CountDownLatch cdl) {
			this.cdl = cdl;
		}

		@Override
		public void run() {
			log.info("执行任务");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			log.info("执行完毕");
			cdl.countDown();
		}
	}

	public static void test() {
		int works = 10;
		CountDownLatch cdl = new CountDownLatch(works);	// 初始化任务计数器
		ExecutorService es = Executors.newCachedThreadPool();
		for (int i = 0; i < works; i++) {
			es.submit(new RCntDownLatchWork(cdl));
		}

		for (int i = 0; i < 2; i++) {
			es.submit(new RCntDownLatchBoss(cdl));
		}

		log.info("wait for all work complete");
		es.shutdown();
	}
}
